import ApiError from '../../error/ApiError'
import ApiErrorNames from '../../error/ApiErrorNames'
import alipayModo from '../../utils/alipayModo'
import AiPayOrder from '../../model/AiPayOrder'
// import fs from 'fs'
import DlyadminAigoods, { typeMap } from '../../model/dlyadminAigoods'
import AiUser from '../../model/AiUser'
import shop from "../../model/shop";
import qianchuanAdShop from "../../model/qianchuanAdShop"
import moment from 'moment'
// const pritNumConfg = [{
// 	prit: 100,
// 	num: 1000
// }]
const alipay = new alipayModo()
function getStartTimeAndEndTime(config) {
	const { timenum, selectTiemtype } = config
	console.log('configconfigconfig', config)
	// selectTiemtype 1 天 2 月 3 年
	let startTime = moment(new Date())
	const endTime = moment(new Date())
	if (selectTiemtype == 1) {
		endTime.add(timenum, 'days')
	}
	if (selectTiemtype == 2) {
		endTime.add(timenum, 'months')
	}
	if (selectTiemtype == 3) {
		endTime.add(timenum, 'years')
	}
	return {
		startTime,
		endTime: endTime,
	}
}
class Alipay {
	static async pay(ctx) {
		// console.log('AiRsq', ctx.request.body)
		if (!ctx.request.body) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		// good_type = 1 , 配置好的 2 自定义
		// good_id = ， 配置id

		let {
			pay_type,
			subject = '自定义充值',
			total_amount,
			qr_pay_mode = '',
			junp_type = true,
			qrcode_width = 100,
			goods_detail = null,
			good_type = '1',
			good_id = '',
			store_id = '', // 可作为记录代理使用
			invoice_info = null, // 后期可能开票需要使用
			returnUrl, // 回调地址
			func_name,
			shop_id,
			aavid = '',
		} = ctx.request.body
		func_name = func_name || 'ai'
		const getUserData = JSON.parse(ctx.request.header.jwtuserinfo)
		// console.log('getUserData', getUserData)

		if (func_name === 'jiance') {
			if (!shop_id) {
				throw new ApiError(ApiErrorNames.selectInDengtData('缺少必要参数'))
			}

			const shopModel = await shop.findOne({
				shop_id: shop_id,
				// aiUserId: getUserData._id
			})
			if (!shopModel) {
				throw new ApiError(ApiErrorNames.selectInDengtData('店铺不存在'))
			}
		}

		if (!typeMap.has(func_name) && func_name !== 'smsBuy') {
			throw new ApiError(ApiErrorNames.selectInDengtData('错误的请求'))
		}


		let integral = 0
		let send_integral = 0
		if (!pay_type || !good_type) {
			console.log('pay_type', pay_type, good_type)
			throw new ApiError(ApiErrorNames.selectInDengtData('缺少必要参数222'))
		}

		if (
			good_type == '2' &&
			(!total_amount || isNaN(total_amount * 1) || total_amount * 1 <= 0)
		) {
			throw new ApiError(
				ApiErrorNames.selectInDengtData('充值金额必填且必须大于0')
			)
		}
		if (good_type == '2') {
			integral = total_amount * 100 // 自定义金额没有的送 后期可以给代理
		}
		console.log('good_type', good_type, good_id)
		if (good_type == '1' && !good_id) {
			throw new ApiError(ApiErrorNames.selectInDengtData('缺少必要参数'))
		}
		if (good_type == '1' && good_id) {
			const getAigoods = await DlyadminAigoods.findOne({
				_id: good_id,
				status: '1',
			})
			console.log('getAigoods00', getAigoods)
			// console.log('判断金额是不是为0', getAigoods)
			if (getAigoods.type === 'qianchuanQY' && getAigoods.price === 0) {

				// 查询当前用户店铺是不是已经存在
				const userBuyShiyon = await AiPayOrder.findOne({
					order_shop_id: shop_id,
					total_amount: getAigoods.price,
					func_name: 'qianchuanQY'
				})

				if (userBuyShiyon) {
					return ctx.body = {
						code: 401,
						msg: '您已订购过试用服务，无法重新订购',
					}
				}
				// 试用订单 直接送





				// 1.创建一个试用订单

				const addPayOrderDataae = {
					subject: getAigoods.name,
					total_amount: 0,
					pay_type,
					store_id,
					returnUrl,
					order_user_id: getUserData._id,
					order_shop_id: shop_id,
					integral,
					send_integral,
					good_id,
					func_name,
					aavid,
					status: '1'
				}
				for (let key in addPayOrderDataae) {
					if (!addPayOrderDataae[key] && addPayOrderDataae[key] !== 0) {
						delete addPayOrderDataae[key]
					}
				}
				// console.log('addPayOrderData', addPayOrderDataae)
				// return ctx.body = '等待支付'
				const getAter = await AiPayOrder.create(addPayOrderDataae)
				// console.log('getAter', getAter)


				const shopModel = await shop.findOne({
					shop_id: shop_id,
					// aiUserId: getUserData._id
				})
				if (!shopModel) {
					throw new ApiError(ApiErrorNames.selectInDengtData('店铺不存在'))
				}
				const serverTime = getStartTimeAndEndTime(getAigoods)
				// console.log('serverTime', serverTime)
				const buyQianchuangAppTime = await qianchuanAdShop.findOne({
					shopInfo: shopModel._id,
					aavid: aavid
				})
				if (!buyQianchuangAppTime) {
					await qianchuanAdShop.create({
						shopInfo: shopModel._id,
						aavid: aavid,
						service_start_time: serverTime.startTime,
						service_end_time: serverTime.endTime,
						current_service_order_id: getAter._id,
					})
				} else {
					if (new Date().getTime() > buyQianchuangAppTime.service_end_time) {
						await qianchuanAdShop.updateMany({
							shopInfo: getShopData._id,
						}, {
							$set: {
								service_end_time: serverTime.endTime,
								current_service_order_id: getAter._id,
							}
						})
					}
					if (new Date().getTime() <= buyQianchuangAppTime.service_end_time) {
						const { timenum, selectTiemtype } = getAigoods
						// if (selectTiemtype == '1') {
						// 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'day')
						// }
						// if (selectTiemtype == '2') {
						// 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'month')
						// }
						// if (selectTiemtype == '3') {
						// 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'year')


						// }
						// getQiancuanserver.save()
						let endtime = buyQianchuangAppTime.service_end_time
						if (selectTiemtype == '1') {
							endtime = moment(buyQianchuangAppTime.service_end_time).add(timenum, 'day')
						}
						if (selectTiemtype == '2') {
							endtime = moment(buyQianchuangAppTime.service_end_time).add(timenum, 'month')
						}
						if (selectTiemtype == '3') {
							endtime = moment(buyQianchuangAppTime.service_end_time).add(timenum, 'year')
						}
						await qianchuanAdShop.updateMany({
							shopInfo: shopModel._id,
						}, {
							$set: {
								service_end_time: endtime,
								current_service_order_id: getAter._id,
							}
						})
					}
				}

				// const addOrReforShopAdList = await qianchuanAdShop.findOneAndUpdate({
				// 	shopInfo: shopModel._id,
				// 	aavid: aavid
				// }, {
				// 	$set: {
				// 		service_start_time: serverTime.startTime,
				// 		service_end_time: serverTime.endTime,
				// 		current_service_order_id: getAter._id,
				// 	}
				// }, { new: true, upsert: true })
				// console.log('新增记录成功', addOrReforShopAdList)
				return ctx.body = {
					code: 1,
					msg: '下单成功',
				}
			}
			if (getAigoods.type === 'qianchuanQY' && getAigoods.price === 0.1) {
				const userBuyShiyon = await AiPayOrder.findOne({
					order_shop_id: shop_id,
					total_amount: 0.1,
					func_name: 'qianchuanQY',
					status: '1'
				})

				if (userBuyShiyon) {
					return ctx.body = {
						code: 401,
						msg: '您已订购过试用服务，无法重新订购',
					}
				}
			}
			if (!getAigoods) {
				throw new ApiError(
					ApiErrorNames.selectInDengtData('商品ID不存在')
				)
			}
			if (getAigoods.type !== func_name) {
				throw new ApiError(
					ApiErrorNames.selectInDengtData('无效的请求')
				)
			}
			total_amount = getAigoods.price
			subject = getAigoods.name
			integral = getAigoods.integral
			send_integral = getAigoods.giveintegral
		}

		const addPayOrderData = {
			subject,
			total_amount,
			pay_type,
			store_id,
			returnUrl,
			order_user_id: getUserData._id,
			order_shop_id: shop_id,
			integral,
			send_integral,
			good_id,
			func_name,
			aavid
		}
		for (let key in addPayOrderData) {
			if (!addPayOrderData[key]) {
				delete addPayOrderData[key]
			}
		}
		console.log('addPayOrderData', addPayOrderData)
		// return ctx.body = '等待支付'
		const getAter = await AiPayOrder.create(addPayOrderData)
		console.log('getAter', getAter)
		const bizContent = {
			out_trade_no: getAter._id + '',
			subject,
			// body: "234",
			total_amount,
			qr_pay_mode,
			qrcode_width: qr_pay_mode && qr_pay_mode == '4' ? qrcode_width : '',
			goods_detail,
			returnUrl,
			junp_type,
			store_id,
			invoice_info,
		}
		console.log('bizContent', bizContent)
		// return ctx.body = '等待支付'
		const getPayUrl = alipay.pay(bizContent)
		// if (getPayUrl.code)
		getAter.pay_html = getPayUrl.data
		await getAter.save()
		// console.log('alipay', getPayUrl)
		// 保存对应记录
		ctx.body = getPayUrl
	}
	static async payCallback(ctx) {
		console.log('支付宝交易结果==============》〉》〉》〉》〉》〉》〉》〉')
		console.log('payCallback', ctx.request.body)
		const getData = alipay.checkNotifySign(ctx.request.body)
		if (getData.code) {
			ctx.body = 'fail'
			return
		}
		// console.log('getData', getData.data)
		const {
			out_trade_no,
			notify_type,
			trade_status,
			gmt_payment,
			trade_no,
		} = getData.data
		const getOrderData = await AiPayOrder.findById(out_trade_no)


		// console.log('getOrderData', getOrderData)
		// return
		if (!getOrderData) {
			ctx.body = 'fail'
			return
		}
		if (getOrderData.status !== '0') {
			ctx.body = 'success'
			return
		}
		let updateOrderData = {
			trade_no,
		}
		if (notify_type == 'trade_status_sync') {
			if (
				trade_status == 'TRADE_SUCCESS' ||
				trade_status == 'TRADE_FINISHED'
			) {
				Object.assign(updateOrderData, {
					status: '1',
					gmt_payment,
				})

				if (getOrderData.func_name && getOrderData.func_name == 'smsBuy') {
					const getItemId = await AiUser.findById(getOrderData.order_user_id)
					// console.log('getItemId', getItemId)
					if (!getItemId) {
						ctx.body = 'fail'
						return
					}
					getItemId.smsNum = (getItemId.smsNum + getOrderData.total_amount * 10).toFixed() * 1
					await getItemId.save()

				} else if (getOrderData.func_name && getOrderData.func_name === 'jiance') {
					const shopModel = await shop.findOne({
						shop_id: getOrderData.order_shop_id,
						// aiUserId: getOrderData.order_user_id
					})
					console.log('检测 支付回调', shopModel)
					if (!shopModel) {
						ctx.body = 'fail'
						return
					}
					console.log('shopModel', shopModel)
					shopModel.jianceScore = ((shopModel.jianceScore || 0) + Number(getOrderData.integral || 0)).toFixed() * 1
					shopModel.jianceSendScore = ((shopModel.jianceSendScore || 0) + (getOrderData.send_integral || 0)).toFixed() * 1

					await shopModel.save()
					ctx.body = 'success'
				} else if (getOrderData.func_name && getOrderData.func_name === 'qianchuanQY') {
					// 前期先是所有端口 避免后期因为端口问题新增

					// 更新 qianchuanAdShop 表
					const getShopData = await shop.findOne({
						shop_id: getOrderData.order_shop_id,

						// aiUserId: payResult.order_user_id
					})
					if (!getShopData) {
						throw new ApiError(
							ApiErrorNames.selectInDengtData('店铺不存在')
						)
					}
					// 先判断当前试用的服务是否到期 或者即将到期5分钟 直接更新
					const getQiancuanserver = await qianchuanAdShop.findOne({
						shopInfo: getShopData._id,
						// 后期考虑是否加入aavid

					})
					const getGoodInfo = await DlyadminAigoods.findOne({
						_id: getOrderData.good_id,
						status: '1',
					})
					if (!getGoodInfo) {
						throw new ApiError(
							ApiErrorNames.selectInDengtData('商品不存在')
						)
					}
					console.log('getGoodInfo', getGoodInfo)
					const serverTime = getStartTimeAndEndTime(getGoodInfo)
					if (!getQiancuanserver) {
						await qianchuanAdShop.create({
							shopInfo: getShopData._id,
							aavid: getOrderData.aavid,
							service_start_time: serverTime.startTime,
							service_end_time: serverTime.endTime,
							current_service_order_id: getOrderData._id,
						})
					} else {
						// 如果当前时间大于 服务的结束时间 表示已经过期 试用新的时间
						// 如果当前时间小雨 服务结束数据 表示没有过期 时间累积上去
						if (new Date().getTime() > getQiancuanserver.service_end_time) {
							// getQiancuanserver.service_start_time = serverTime.startTime
							// getQiancuanserver.service_end_time = serverTime.endTime
							// 批量更新 qianchuanAdShop 的·shopInfo

							await qianchuanAdShop.updateMany({
								shopInfo: getShopData._id,
							}, {
								$set: {
									service_end_time: serverTime.endTime,
									current_service_order_id: getOrderData._id,
								}
							})

						}
						if (new Date().getTime() <= getQiancuanserver.service_end_time) {
							const { timenum, selectTiemtype } = getGoodInfo
							// if (selectTiemtype == '1') {
							// 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'day')
							// }
							// if (selectTiemtype == '2') {
							// 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'month')
							// }
							// if (selectTiemtype == '3') {
							// 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'year')


							// }
							// getQiancuanserver.save()
							let endtime = getQiancuanserver.service_end_time
							if (selectTiemtype == '1') {
								endtime = moment(getQiancuanserver.service_end_time).add(timenum, 'day')
							}
							if (selectTiemtype == '2') {
								endtime = moment(getQiancuanserver.service_end_time).add(timenum, 'month')
							}
							if (selectTiemtype == '3') {
								endtime = moment(getQiancuanserver.service_end_time).add(timenum, 'year')
							}
							await qianchuanAdShop.updateMany({
								shopInfo: getShopData._id,
							}, {
								$set: {
									service_end_time: endtime,
									current_service_order_id: getOrderData._id,
								}
							})
						}

					}

				} else {
					const getItemId = await AiUser.findById(getOrderData.order_user_id)
					// console.log('getItemId', getItemId)
					if (!getItemId) {
						ctx.body = 'fail'
						return
					}
					getItemId.remainScore = (getItemId.remainScore + getOrderData.integral).toFixed() * 1
					getItemId.remainSendScore = (getItemId.remainSendScore + getOrderData.send_integral).toFixed() * 1
					await getItemId.save()

				}


				// 这里修改用户的金额变化
			}
			if (trade_status == 'TRADE_CLOSED') {
				Object.assign(updateOrderData, {
					status: '3',
					gmt_close: new Date(),
				})
			}
			Object.assign(getOrderData, updateOrderData)
			getOrderData.save()
		}

		ctx.body = 'success'
	}
	static async payResult(ctx) {
		const { out_trade_no } = ctx.request.query || {}
		if (!out_trade_no) {
			throw new ApiError(ApiErrorNames.selectInDengtData('缺少必要参数'))
		}
		const payResult = await AiPayOrder.findById(out_trade_no)
		console.log('payResult', payResult)
		if (!payResult) {
			throw new ApiError(ApiErrorNames.selectInDengtData('订单不存在'))
		}
		if (payResult.status == '0') {
			const getRecoderData = await alipay.query({
				out_trade_no,
			})

			console.log('getRecoderData', getRecoderData)
			payResult.buyerLogonId = getRecoderData.buyerLogonId

			if (getRecoderData.tradeStatus === 'TRADE_SUCCESS' || getRecoderData.tradeStatus === 'TRADE_FINISHED') {
				payResult.status = '1'
				payResult.gmt_payment = getRecoderData.gmtPayment
				payResult.trade_no = getRecoderData.tradeNo
				await payResult.save()


				// console.log('getItemId', getItemId)
				// getItemId.remainScore = (getItemId.remainScore + payResult.integral).toFixed() * 1
				if (payResult.func_name && payResult.func_name == 'smsBuy') {
					const getItemId = await AiUser.findById(payResult.order_user_id)
					if (!getItemId) {
						throw new ApiError(
							ApiErrorNames.selectInDengtData('用户不存在')
						)
					}
					getItemId.smsNum = (getItemId.smsNum + payResult.total_amount * 10).toFixed() * 1
					await getItemId.save()

				} else if (payResult.func_name && payResult.func_name === 'jiance') {
					const shopModel = await shop.findOne({
						shop_id: payResult.order_shop_id,
						// aiUserId: payResult.order_user_id
					})
					if (!shopModel) {
						throw new ApiError(
							ApiErrorNames.selectInDengtData('店铺不存在')
						)
					}
					// console.log('shopModel000', shopModel)
					shopModel.jianceScore = ((shopModel.jianceScore || 0) + payResult.integral).toFixed() * 1
					shopModel.jianceSendScore = ((shopModel.jianceSendScore || 0) + (payResult.send_integral || 0)).toFixed() * 1

					await shopModel.save()
				} else if (payResult.func_name && payResult.func_name === 'qianchuanQY') {
					// 前期先是所有端口 避免后期因为端口问题新增

					// 更新 qianchuanAdShop 表
					const getShopData = await shop.findOne({
						shop_id: payResult.order_shop_id,

						// aiUserId: payResult.order_user_id
					})
					if (!getShopData) {
						throw new ApiError(
							ApiErrorNames.selectInDengtData('店铺不存在')
						)
					}
					// 先判断当前试用的服务是否到期 或者即将到期5分钟 直接更新
					const getQiancuanserver = await qianchuanAdShop.findOne({
						shopInfo: getShopData._id,
						// 后期考虑是否加入aavid

					})
					const getGoodInfo = await DlyadminAigoods.findOne({
						_id: payResult.good_id,
						status: '1',
					})
					if (!getGoodInfo) {
						throw new ApiError(
							ApiErrorNames.selectInDengtData('商品不存在')
						)
					}
					console.log('getGoodInfo', getGoodInfo)
					const serverTime = getStartTimeAndEndTime(getGoodInfo)
					if (!getQiancuanserver) {
						await qianchuanAdShop.create({
							shopInfo: getShopData._id,
							aavid: payResult.aavid,
							service_start_time: serverTime.startTime,
							service_end_time: serverTime.endTime,
							current_service_order_id: payResult._id,
						})
					} else {
						// 如果当前时间大于 服务的结束时间 表示已经过期 试用新的时间
						// 如果当前时间小雨 服务结束数据 表示没有过期 时间累积上去
						if (new Date().getTime() > getQiancuanserver.service_end_time) {
							// getQiancuanserver.service_start_time = serverTime.startTime
							// getQiancuanserver.service_end_time = serverTime.endTime
							// 批量更新 qianchuanAdShop 的·shopInfo

							await qianchuanAdShop.updateMany({
								shopInfo: getShopData._id,
							}, {
								$set: {
									service_end_time: serverTime.endTime,
									current_service_order_id: payResult._id,
								}
							})

						}
						if (new Date().getTime() <= getQiancuanserver.service_end_time) {
							const { timenum, selectTiemtype } = getGoodInfo
							// if (selectTiemtype == '1') {
							// 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'day')
							// }
							// if (selectTiemtype == '2') {
							// 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'month')
							// }
							// if (selectTiemtype == '3') {
							// 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'year')


							// }
							// getQiancuanserver.save()
							let endtime = getQiancuanserver.service_end_time
							if (selectTiemtype == '1') {
								endtime = moment(getQiancuanserver.service_end_time).add(timenum, 'day')
							}
							if (selectTiemtype == '2') {
								endtime = moment(getQiancuanserver.service_end_time).add(timenum, 'month')
							}
							if (selectTiemtype == '3') {
								endtime = moment(getQiancuanserver.service_end_time).add(timenum, 'year')
							}
							await qianchuanAdShop.updateMany({
								shopInfo: getShopData._id,
							}, {
								$set: {
									service_end_time: endtime,
									current_service_order_id: payResult._id,
								}
							})
						}

					}
				} else {
					const getItemId = await AiUser.findById(payResult.order_user_id)
					if (!getItemId) {
						throw new ApiError(
							ApiErrorNames.selectInDengtData('用户不存在')
						)
					}
					getItemId.remainScore =
						(getItemId.remainScore + payResult.integral).toFixed() *
						1
					getItemId.remainSendScore =
						(
							getItemId.remainSendScore + payResult.send_integral
						).toFixed() * 1
					await getItemId.save()

				}
				// await getItemId.save()

				ctx.body = '支付成功'
			}
			if (getRecoderData.tradeStatus === 'TRADE_CLOSED') {
				payResult.status = '3'
				payResult.gmt_close = getRecoderData.gmtClose
				// payResult.buyerLogonId = getRecoderData.buyerLogonId
				await payResult.save()
			}
			if (getRecoderData.tradeStatus === 'WAIT_BUYER_PAY') {
				payResult.status = '0'
				// payResult.buyerLogonId = getRecoderData.buyerLogonId
				await payResult.save()
			}
		}
		// console.log('payResult', payResult)
		ctx.body = payResult
	}
	static async orderRecords(ctx) {
		const aiUserData = JSON.parse(ctx.request.header.jwtuserinfo)
		const { pageSize = 20, page = 1, status = '' } = ctx.query || {}
		console.log('aiUserData', aiUserData)
		const getOrderLogsData = {
			order_user_id: aiUserData._id,
			status,
		}
		for (let key in getOrderLogsData) {
			if (getOrderLogsData[key] === '') {
				delete getOrderLogsData[key]
			}
		}
		const getOrderData = await AiPayOrder.find(getOrderLogsData)
			.sort({ createTime: -1 })
			.limit(pageSize * 1)
			.skip((page - 1) * pageSize)
		// console.log('getOrderData', getOrderData)
		const total = await AiPayOrder.find(getOrderLogsData).countDocuments()
		ctx.body = {
			list: getOrderData,
			total,
		}
	}
	static async closeOrder(ctx) {
		const aiUserData = JSON.parse(ctx.request.header.jwtuserinfo)
		const { out_trade_no } = ctx.query || {}
		if (!out_trade_no) {
			throw new ApiError(ApiErrorNames.selectInDengtData('缺少必要参数'))
		}
		const getOrderData = await AiPayOrder.findOne({
			_id: out_trade_no,
			order_user_id: aiUserData._id,
		}).catch((err) => {
			throw new ApiError(ApiErrorNames.selectInDengtData('订单不存在'))
		})
		if (!getOrderData) {
			throw new ApiError(ApiErrorNames.selectInDengtData('订单不存在'))
		}
		if (getOrderData.status == '0') {
			const getRecoderData = await alipay.close({
				out_trade_no,
			})
			console.log('getRecoderData', getRecoderData)
			getOrderData.status = '3'
			getOrderData.gmt_close = new Date()
			await getOrderData.save()

			ctx.body = '订单关闭成功'
			// if (getRecoderData.code == '10000') {
			// 	getOrderData.status = '3'
			// 	getOrderData.gmt_close = new Date()
			// 	await getOrderData.save()
			// 	ctx.body = '订单关闭成功'
			// 	return
			// } else {

			// }
			return
		}
		ctx.body = '该订单不可操作'
	}
}

export default Alipay
